package cn.harry.modular.sys.service.impl;

import cn.harry.common.utils.IpUtil;
import cn.harry.common.utils.RedisKeys;
import cn.harry.common.utils.RedisUtils;
import cn.harry.common.utils.ServletUtils;
import cn.harry.modular.sys.mapper.SysUserLoginLogMapper;
import cn.harry.modular.sys.domain.SysUser;
import cn.harry.modular.sys.domain.SysUserLoginLog;
import cn.harry.modular.sys.service.SysUserLoginLogService;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 后台用户登录日志表
 *
 * @author honghh Date 2019-10-12 10:55:44 Copyright (C) www.tech-harry.cn
 */
@Slf4j
@Service
public class SysUserLoginLogServiceImpl
		extends ServiceImpl<SysUserLoginLogMapper, SysUserLoginLog>
		implements SysUserLoginLogService {

	@Override
	public int clean() {
		return this.baseMapper.clean();
	}

	@Override
	public List<SysUserLoginLog> getExportList(SysUserLoginLog loginLog) {
		LambdaQueryWrapper<SysUserLoginLog> wrapper = new LambdaQueryWrapper<>(loginLog);
		if (StrUtil.isNotEmpty(loginLog.getBeginTime())) {
			wrapper.gt(SysUserLoginLog::getCreateTime, loginLog.getBeginTime());
		}

		if (StrUtil.isNotEmpty(loginLog.getEndTime())) {
			wrapper.lt(SysUserLoginLog::getCreateTime, loginLog.getEndTime());
		}
		return list(wrapper);
	}

	@Override
	@Async
	public void recordLoginInfo(SysUser sysUser, String token, String expiration) {
		HttpServletRequest request = ServletUtils.getRequest();
		String ip = IpUtil.getIp(request);
		String browser = IpUtil.getBrowser(request);
		String address = IpUtil.getAddress(ip);
		String os = IpUtil.getOs(request);
		// redis存储token
		RedisUtils.set(RedisKeys.getTokenByUsername(sysUser.getUsername()), token,
				Long.parseLong(expiration));

		// 过期时间 = 当前时间 + 过期时间
		Date expTime = new Date(
				System.currentTimeMillis() + Long.parseLong(expiration) * 1000);
		SysUserLoginLog loginLog = new SysUserLoginLog();
		loginLog.setUserId(sysUser.getId());
		loginLog.setUsername(sysUser.getUsername());
		loginLog.setNickName(sysUser.getNickName());
		loginLog.setIp(ip);
		loginLog.setBrowser(browser);
		loginLog.setOs(os);
		loginLog.setAddress(address);
		loginLog.setToken(token);
		loginLog.setExpTime(expTime);
		save(loginLog);
	}

}